package strategies;

import exceptions.DatabaseException;
import general.IContext;

/**
 *
 * @author Alejandro
 */
public abstract class AddRowStrategy extends AbstractStrategy {

    final static String ERROR_NUMBER_TYPE = "Fields that require number type have incorrect value";
    final static String ERROR_UPDATE = "Updating database failed";
    final static String ERROR_MISSING_VALUES = "Not all fields were filled or incorrect values in fields";
    final static String ERROR_ADD = "Adding to database failed";
    protected boolean isValid = false;
    protected String date;

    protected abstract void addRow();

    protected abstract Object createObject();

    @Override
    public void executeOperation(IContext context) {
        prepareContext(context);
        if (dao != null) {
            if (pp.getParamMap().containsKey("table-selection")) {
                date = "";
                try {
                    addRow();
                } catch (NumberFormatException nfe) {
                    op.putErrorReport(ERROR_NUMBER_TYPE, nfe.getMessage());
                }
                if (isValid) {
                    Object e = createObject();
                    int result = 0;
                    String errorMessage = "";
                    try {
                        result = dao.insert(e);
                    } catch (DatabaseException de) {
                        result = 0;
                        errorMessage = de.getMessage();
                    }
                    if (result == 0) {
                        op.putErrorReport(ERROR_ADD, errorMessage);
                    } else {
                        op.putSuccessReport(result + " row inserted");
                    }
                } else {
                    op.putErrorReport(ERROR_MISSING_VALUES, "");
                }
            }
        }
    }
}
